package com.hogan.hoganproject.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.TextViewCompat;

import com.hogan.hoganproject.R;

import java.util.Random;

/**
 * Author: chenhu
 * Time: 2020/9/18 11:03
 * Description do somethings
 */
public class ContactsHeadView extends androidx.appcompat.widget.AppCompatTextView {
    private boolean isRandomColor;
    private int mBgColor;
    private Context mContext;
    private String mFirstName;
    private Random mRandom;

    public ContactsHeadView(@NonNull Context context) {
        this(context, null);
    }

    public ContactsHeadView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mRandom = new Random();
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.ContactsHeadView);
        isRandomColor = typedArray.getBoolean(R.styleable.ContactsHeadView_random, true);
        mBgColor = typedArray.getColor(R.styleable.ContactsHeadView_textColor, mContext.getColor(R.color.colorPrimary));
        mFirstName = typedArray.getString(R.styleable.ContactsHeadView_textName);
        typedArray.recycle();
        initView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int minSize = Math.min(width, height);
        setMeasuredDimension(minSize, minSize);
    }

    private void initView() {
        if (TextUtils.isEmpty(mFirstName)) {
            return;
        }
        if (isRandomColor) {
            mBgColor = getRandomColor();
        }
        setGravity(Gravity.CENTER);

        TextViewCompat.setAutoSizeTextTypeWithDefaults(this, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
        setBackgroundResource(R.drawable.shape_bg);
        GradientDrawable drawable = (GradientDrawable) getBackground();
        drawable.setColor(mBgColor);
        setBackgroundDrawable(drawable);
        setText(mFirstName);//取首字符显示
    }

    private int getRandomColor() {
        String[] colorArray = mContext.getResources().getStringArray(R.array.contacts_color);
        int value = mRandom.nextInt(colorArray.length);
        return Color.parseColor(colorArray[value]);
    }

    public void setHeadName(String name) {
        mFirstName = name;
        initView();
    }
}
